#= require jquery.tablesorter.js

(($) ->
  
  $powergridId = 0
  
  computeColumnWidths = (el, columns) ->
    totalWidth = el[0].offsetWidth
    widths = []
    usedWidth = 0
    nWantingSpace = 0
    for column in columns
      widths.push column.minWidth or 100
      usedWidth += column.minWidth or 100
      nWantingSpace++ unless column.fixedWidth
    leftWidth = totalWidth - usedWidth
    return widths if leftWidth <= 0
    extraSpace = leftWidth / nWantingSpace
    for column, i in columns
      widths[i] += extraSpace
    widths
    
  layout = (columnNumber, widths, stylesheet, pgid) ->
    style_text = ''
    for i in [0..(columnNumber-1)]
      style_text += ".pg-#{pgid}-col-#{i} { width: #{widths[i]}px }"
    stylesheet.html style_text
  
  $.fn.powergrid = (columns, items) ->
    console.log items
    # The global ID for CSS classes
    pgid = $powergridId++
    
    # Setup elements
    this.addClass('powergrid table table-bordered table-striped').data('columns', columns).data('pgid', pgid)
    head_wrapper = $(document.createElement 'thead').append('<tr></tr>')
    head = head_wrapper.children()
    body = $(document.createElement 'tbody').css { overflow: 'auto' }
    stylesheet = $(document.createElement 'style').attr('type', 'text/css')
      .attr('id', 'pgstyle-' + pgid)
    
    # Layout
    widths = computeColumnWidths this, columns
    data_mappings = []
    
    layout columns.length, widths, stylesheet, pgid
    
    # Add columns and items
    for column, i in columns
      head.append """
        <th class="pg-#{pgid}-col-#{i}">#{column.title}</th>
      """
      data_mappings.push column.id
    
    for item in items
      row = $ document.createElement 'tr'
      for id, i in data_mappings
        row.append """
          <td class="pg-#{pgid}-col-#{i}">#{item[id]}</td>
        """
      body.append row
    
    # Add everything to the page
    $('head').append stylesheet
    this.append head_wrapper
    this.append body
    
    # Setup other plugins
    this.tablesorter()

  $.fn.powerlayout = ->
    return unless this.hasClass 'powergrid'
    console.log "Power layout ready!"
    pgid = this.data 'pgid'
    widths = computeColumnWidths this, this.data('columns')
    layout this.data('columns').length, widths, $('#pgstyle-' + pgid), pgid
  
)(jQuery)